﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jw.Models;
using Jw.Web.Areas.Pacm.Common;
using System.Web.Http;
using Jw.Core;
using Jw.Utils;
using CommonUtilities.DataBase;
using System.Data;

namespace Jw.Web.Areas.Pacm.Controllers
{
    public class JszbController : Controller
    {
        //
        // GET: /Pacm/Jszb/

        /// <summary>
        /// 技术指标月报
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var codeService = new sys_codeService();
            var model = new
            {
                idField = "", //主键
                urls = new
                {
                    query = "/api/Pacm/Jszb/GetJszbData"
                },
                resx = PacmHelper.GetIndexResx("技术指标曲线"),
                dataSource = new
                {
                    yearItems = codeService.GetYearItems(),
                    monthItems = codeService.GetMonthItems(),
                    zblxItems = codeService.GetDjzbItems() //电解指标
                },
                form = new
                {
                    Ch = "1001", //槽号
                    Year = DateTime.Now.Year,
                    Month = DateTime.Now.Month,
                    Zblx = "Scsj_Cy_Gzdl"//"槽温度"
                }

            };
            return View(model);
        }


        /// <summary>
        /// 月度技术指标_对比
        /// </summary>
        /// <returns></returns>
        public ActionResult Index2()
        {
            var codeService = new sys_codeService();
            var model = new
            {
                idField = "", //主键
                urls = new
                {
                    query = "/api/Pacm/Jszb/GetJszbData2"
                },
                resx = PacmHelper.GetIndexResx("月度技术指标对比"),
                dataSource = new
                {
                    yearItems = codeService.GetYearItems(),
                    monthItems = codeService.GetMonthItems(),
                    zblxItems = codeService.GetDjzbItems() //电解指标
                },
                form = new
                {
                    Ch = "1001", //槽号
                    Zblx = "Scsj_Cy_Gzdl",//"槽温度"
                    Year = DateTime.Now.Year,  //当前年
                    Month = DateTime.Now.Month, //当前月
                    hYear = DateTime.Now.Year, //对比年
                    hMonth = DateTime.Now.AddMonths(-1).Month //对比月
                }
            };
            return View(model);
        }
    }

    /// <summary>
    /// api
    /// </summary>
    public class JszbApiController : ApiController
    {
        /// <summary>
        /// 得到技术指标数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public dynamic GetJszbData(RequestWrapper query)
        {
            //槽号、年、月、指标类型
            string sCh = ZConvert.To<string>(query["Ch"], "");
            string sYear = ZConvert.To<string>(query["Year"], "");
            string sMonth = ZConvert.To<string>(query["Month"], "");
            string sZblx = ZConvert.To<string>(query["Zblx"], "");

            if (string.IsNullOrEmpty(sYear)) sYear = DateTime.Now.Year.ToString();
            if (string.IsNullOrEmpty(sMonth))
            {
                sMonth = DateTime.Now.ToString("MM");
            }
            else
            {
                sMonth = sMonth.PadLeft(2, '0');
            }

            string sRq = sYear + "-" + sMonth;
            string sReutrn = "没有数据...";
            using (var db = Db.Context("Pacm"))
            {
                string categories = "";
                string dataset = "";
                string caption = "";
                string subcaption = "";
                string sHead = "";
                string sConnect = db.Data.ConnectionString;
                SQLHelper dbhelper = new SQLHelper(sConnect);
                string sText = string.Format(@"select scsj_ch,datepart(dd,Scsj_rq) as Day, {0}  as value from  p_scsj 
                                              where convert(varchar(7),Scsj_Rq,120) = '{1}' and Scsj_Ch = '{2}' order by Scsj_Rq asc", sZblx, sRq, sCh);
                DataTable dt = dbhelper.GetDataTable(sText, new System.Data.SqlClient.SqlParameter[0]);
                //槽号 + 指标
                string zbMc = new sys_codeService().GetDjzbItems().Find(m => m.value == sZblx).text;
                caption = sCh + ":" + zbMc;
                subcaption = "月份:" + sRq;
                // dt.Compute("max(id)", "");
                object sMax = dt.Compute("max(value)", "");
                sHead = string.Format(@"<chart compactDataMode='1' dataSeparator='|' caption='{0}' subcaption='{1}' axis='linear' numberPrefix='' formatNumberScale='0' decimals='3' yAxisMaxValue ='{2}'
                                        bgColor='F7F7F7, E9E9E9' divLineColor='CC3300' lineColor='91AF46' allowPinMode='0' enableIconMouseCursors='0' dynamicAxis='1' palette='4'>", caption, subcaption, sMax.ToString() == "" ? 0 : Math.Round(Convert.ToDouble(sMax.ToString()), 3) * 1.2);
                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    categories += dt.Rows[i]["Day"].ToString() + "|";
                    double dvalue = dt.Rows[i]["value"] == DBNull.Value ? 0 : Convert.ToDouble(dt.Rows[i]["value"]);
                    dataset += Math.Round(dvalue, 3).ToString() + "|";
                }
                sReutrn = string.Format(@"{0}<categories>{1}</categories><dataset seriesName='{3}' anchorBgColor ='FF0080' color='FF0080'  lineThickness='1'>{2}</dataset></chart>", sHead, categories, dataset, zbMc);
            }
            return sReutrn;

        }

        /// <summary>
        /// 月度技术指标对比分析
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public dynamic GetJszbData2(RequestWrapper query)
        {
            //槽号、年、月、指标类型
            string sCh = ZConvert.To<string>(query["Ch"], "");
            string sZblx = ZConvert.To<string>(query["Zblx"], "");
            //当前年、当前月
            string sYear = ZConvert.To<string>(query["Year"], "");
            string sMonth = ZConvert.To<string>(query["Month"], "");
            //对比年、对比月
            string shYear = ZConvert.To<string>(query["hYear"], "");
            string shMonth = ZConvert.To<string>(query["hMonth"], "");



            if (string.IsNullOrEmpty(sYear)) sYear = DateTime.Now.Year.ToString();
            if (string.IsNullOrEmpty(sMonth))
            {
                sMonth = DateTime.Now.ToString("MM");
            }
            else
            {
                sMonth = sMonth.PadLeft(2, '0');
            }

            string sRq = sYear + "-" + sMonth;
            string sHrq = shYear + "-" + shMonth;
            string sReutrn = "没有数据...";
            using (var db = Db.Context("Pacm"))
            {
                string categories = "";
                string dataset = "";
                string dataset1 = "";
                string caption = "";
                string subcaption = "";
                string sHead = "";
                string sConnect = db.Data.ConnectionString;
                SQLHelper dbhelper = new SQLHelper(sConnect);
                string sText = string.Format(@"select scsj_ch,datepart(dd,Scsj_rq) as Day, {0}  as value from  p_scsj 
                                              where convert(varchar(7),Scsj_Rq,120) = '{1}' and Scsj_Ch = '{2}' order by Scsj_Rq asc", sZblx, sRq, sCh);
                DataTable dt = dbhelper.GetDataTable(sText, new System.Data.SqlClient.SqlParameter[0]);

                sText = string.Format(@"select scsj_ch,datepart(dd,Scsj_rq) as Day, {0}  as value from  p_scsj 
                                              where convert(varchar(7),Scsj_Rq,120) = '{1}' and Scsj_Ch = '{2}' order by Scsj_Rq asc", sZblx, sHrq, sCh);
                DataTable dt2 = dbhelper.GetDataTable(sText, new System.Data.SqlClient.SqlParameter[0]);

                //槽号 + 指标
                caption = sCh + ":" + new sys_codeService().GetDjzbItems().Find(m => m.value == sZblx).text;
                subcaption = string.Format("{0}对比{1}", sRq, sHrq);
                // dt.Compute("max(id)", "");
                object sMax = dt.Compute("max(value)", "");
                object sMax2 = dt2.Compute("max(value)", "");
                //判断最大值
                if (Convert.ToDouble(sMax) < Convert.ToDouble(sMax2)) sMax = sMax2;

                sHead = string.Format(@"<chart compactDataMode='1' dataSeparator='|' caption='{0}' subcaption='{1}' axis='linear' numberPrefix='' formatNumberScale='0' decimals='3' yAxisMaxValue ='{2}' 
                                         bgColor='F7F7F7, E9E9E9' divLineColor='CC3300' lineColor='91AF46' allowPinMode='0' enableIconMouseCursors='0' dynamicAxis='1' palette='4'>", caption, subcaption, sMax.ToString() == "" ? 0 : Math.Round(Convert.ToDouble(sMax.ToString()), 3) * 1.2);

                for (int i = 1; i <= 31; i++)
                {
                    double dvalue = 0;
                    categories += i.ToString() + "|";
                    //当期数据
                    DataRow[] dr = dt.Select("Day='" + i.ToString() + "'");
                    if (dr.Count() == 0)
                    {
                        dataset += "" + "|";
                    }
                    else
                    {
                        dvalue = dr[0]["value"] == DBNull.Value ? 0 : Convert.ToDouble(dr[0]["value"]);
                        dataset += Math.Round(dvalue, 3).ToString() + "|";
                    }
                    //对比数据
                    DataRow[] dr2 = dt2.Select("Day='" + i.ToString() + "'");
                    if (dr2.Count() == 0)
                    {
                        dataset1 += "" + "|";
                    }
                    else
                    {
                        dvalue = dr2[0]["value"] == DBNull.Value ? 0 : Convert.ToDouble(dr2[0]["value"]);
                        dataset1 += Math.Round(dvalue, 3).ToString() + "|";
                    }
                }
                sReutrn = string.Format(@"{0}<categories>{1}</categories><dataset seriesName='{2}' anchorBgColor ='800080' color='800080' lineThickness='1'>{3}</dataset><dataset seriesName='{4}' anchorBgColor ='FF0080' color='FF0080'  lineThickness='1'>{5}</dataset></chart>",
                                    sHead, categories, sRq, dataset, sHrq, dataset1);
            }
            return sReutrn;

        }
    }

}
